package com.archerdu.common.filter;

import java.io.IOException;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import nl.bitwalker.useragentutils.UserAgent;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

import com.archerdu.commons.util.ServletUtil;

/**
 * 访问日志
 * 
 * @projectName springDemo
 * @description 访问日志
 * @author archer du
 * @createDate 2013年9月27日 下午5:24:49
 * @updateUser dxf
 * @updateDate 2013年9月27日 下午5:24:49
 * @updateRemark 新建
 * @version 0.0.1
 */
public class AccessLogFilter implements Filter {

    private static final Logger      LOG              = Logger.getLogger("AccessLog");
    /** 　加密字段参数名 */
    private static final String      ENCRYPT_PARA     = "encryptParas";
    /** 需要加密的字段集合 */
    private static final Set<String> ENCRYPT_PARA_SET = new HashSet<String>();

    @Override
    public void destroy() {
        // Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
            ServletException {
        HttpServletRequest requ = (HttpServletRequest) req;
        UserAgent ua = new UserAgent(requ.getHeader("User-Agent"));

        StringBuffer sb = new StringBuffer(ServletUtil.getIpAddr(requ));
        sb.append(DateFormatUtils.format(new Date(), " [yyyy-MM-dd hh:mm:ss] "));
        sb.append(requ.getProtocol());
        sb.append(" ");
        sb.append(requ.getMethod());
        sb.append(" ");
        sb.append(requ.getRequestURL());
        sb.append(" ");
        sb.append(ServletUtil.parameter2Json(requ, ENCRYPT_PARA_SET));
        sb.append(" ");
        sb.append(ua.getBrowser());
        sb.append(" ");
        sb.append(ua.getBrowserVersion());
        sb.append(" ");
        sb.append(ua.getOperatingSystem());
        sb.append(" Referer: ");
        sb.append(requ.getHeader("Referer"));

        chain.doFilter(req, res);

        sb.append(" ");

        LOG.info(sb.toString());
    }

    @Override
    public void init(FilterConfig conf) throws ServletException {
        // 初始化需要加密的字段
        String paras = conf.getInitParameter(ENCRYPT_PARA);
        if (!StringUtils.isEmpty(paras)) {
            try {
                for (String para : paras.split(",")) {
                    ENCRYPT_PARA_SET.add(para);
                }
            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
            }
        }
    }
}
